package com.qihang.core.dao.impl;

import java.io.Serializable;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.qihang.common.PagerModel;
import com.qihang.core.dao.ArticleDao;
import com.qihang.core.domain.ArticleEntity;

/**
 * @author limn
 *
 */
@Repository("articleDao")
public class ArticleDaoImpl implements ArticleDao {

	@Resource(name="sessionFactory")
	protected SessionFactory sessionFactory;

	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public boolean isExistArticle(ArticleEntity paramArticle) {
		Session session = this.getSession();
		String hql = "select count(1) from ArticleEntity where articleTitle =?";
		Query query = session.createQuery(hql);
		query.setString(0, paramArticle.getArticleTitle());
		Long count = (Long) query.uniqueResult();
		if (count >= 1) {
			return true;
		}
		return false;
	}

	@Override
	public void delArticle(ArticleEntity paramArticle) {
		this.getSession().delete(paramArticle);
//		String hql="delete ArticleEntity as a where a.articleId=?";
//		Query query=this.getSession().createQuery(hql);
//		query.setInteger(0,paramArticle.getArticleId());
//		int success = query.executeUpdate();
		
	}

	@Override
	public void updateArticle(ArticleEntity paramArticle) {
		this.getSession().update(paramArticle);
	}

	@Override
	public PagerModel getArticleList(ArticleEntity paramArticle) {
		Session session = this.getSession();
		String hql = "from ArticleEntity";
		Query query = session.createQuery(hql);
		PagerModel pages = new PagerModel(paramArticle.getPageNo(), 10, query);
		return pages;
	}

	@Override
	public ArticleEntity getArticle(ArticleEntity paramArticle) {
		return (ArticleEntity) this.getSession().get(ArticleEntity.class, paramArticle.getArticleId());
	}

	@Override
	public boolean addArticle(ArticleEntity paramArticle) {
		Serializable succ = this.getSession().save(paramArticle);
		return null == succ ? false : true;
	}
}
